package com.ztzh.temteam.utils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Objects;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ztzh.temteam.example.dto.UploadResp;
import com.ztzh.temteam.example.dto.chat.ChatMessage;
import com.ztzh.temteam.example.dto.chat.ChatRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * ChatMessage
 *
 * @author yiyong
 *
 **/
public class ChatDocUtil {


    public  static  StringBuilder sdf = new StringBuilder();

    public static StringBuilder getSdf() {
        return sdf;
    }

    /**
     * 上传文件
     * @param filePath
     * @param url
     * @param appId
     * @param secret
     * @return
     */
    public UploadResp upload(String filePath, String url, String appId, String secret){
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            File file = new File(filePath);
           // Path path = Paths.get(filePath);
            long ts = System.currentTimeMillis() / 1000;
            String signature = ApiAuthUtil.getSignature(appId, secret, ts);

            // 创建 HttpPost 请求
            HttpPost uploadFile = new HttpPost(url);
            uploadFile.setHeader("appId", appId);
            uploadFile.setHeader("timestamp", String.valueOf(ts));
            uploadFile.setHeader("signature", signature);
            String fileSeparator = File.separator;
            // 构建 MultipartEntityBuilder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file",
                    getClass().getClassLoader().getResourceAsStream( filePath),
                    ContentType.DEFAULT_BINARY,
                    filePath);
            builder.addTextBody("fileType", "wiki", ContentType.TEXT_PLAIN);

            HttpEntity multipart = builder.build();
            uploadFile.setEntity(multipart);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(uploadFile)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 解析响应体
                    HttpEntity responseEntity = response.getEntity();
                    String responseString = EntityUtils.toString(responseEntity);
                    return JSON.parseObject(responseString,UploadResp.class);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException("Request failed", e);
        }

        return null;

    }


    /**
     * 聊天
     * @param chatUrl
     * @param fileId
     * @param question
     * @param appId
     * @param secret
     */
    public void chat(String chatUrl, String fileId, String question, String appId, String secret) throws URISyntaxException {
        ChatMessage message = new ChatMessage();
        message.setRole("user");
        message.setContent(question);
        // 请求内容
        ChatRequest request = ChatRequest.builder()
                .fileIds(Collections.singletonList(fileId))
                .topN(3)
                .messages(Collections.singletonList(message))
                .build();

        // 构造url鉴权
        long ts = System.currentTimeMillis() / 1000;
        String signature = ApiAuthUtil.getSignature(appId, secret, ts);
        String requestUrl = chatUrl + "?" + "appId=" + appId + "&timestamp=" + ts + "&signature=" + signature;


        StringBuffer buffer = new StringBuffer();
        WebSocketClient webSocketClient = new WebSocketClient(new URI(requestUrl)) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                // 连接成功后发送请求
                send(JSONUtil.toJsonStr(request));
            }

            @Override
            public void onMessage(String message) {
                JSONObject jsonObject = JSONUtil.parseObj(message);
                String content = jsonObject.getStr("content");
                if (StrUtil.isNotEmpty(content)) {
                    buffer.append(content);
                    sdf.append(content);
                }
                if (Objects.equals(jsonObject.getInt("status"), 2)) {
                    System.out.println("回答内容：" + buffer);
                    close();
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("WebSocket 连接关闭: " + reason);
                sdf.setLength(0);
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
            }
        };

        webSocketClient.connect();


        //改造代码
//        StringBuffer buffer = new StringBuffer();
//        try {
//            WebSocketClient client = new CustomWebSocketClient(new URI(requestUrl), buffer);
//            client.connectBlocking(); // 等待WebSocket连接
//
//            client.send(JSONUtil.toJsonStr(request)); // 发送消息
//
//            // 由于处理是异步的，可以增加处理逻辑，例如等待关闭等
//        } catch (URISyntaxException | InterruptedException e) {
//            e.printStackTrace();
//        }





        // ws
//        Request wsRequest = (new Request.Builder()).url(requestUrl).build();
//        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
//        StringBuffer buffer = new StringBuffer();
//        WebSocket webSocket = okHttpClient.newWebSocket(wsRequest, new WebSocketListener() {
//            @Override
//            public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
//                super.onClosed(webSocket, code, reason);
//                webSocket.close(1002, "websocket finish");
//                okHttpClient.connectionPool().evictAll();
//            }
//
//            @Override
//            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
//                super.onFailure(webSocket, t, response);
//                webSocket.close(1001, "websocket finish");
//                okHttpClient.connectionPool().evictAll();
//            }
//
//            @Override
//            public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
//                System.out.println(text);
//                JSONObject jsonObject = JSONUtil.parseObj(text);
//                String content = jsonObject.getStr("content");
//                if (StrUtil.isNotEmpty(content)) {
//                    buffer.append(content);
//                }
//                if (Objects.equals(jsonObject.getInt("status"), 2)) {
//                    System.out.println("回答内容：" + buffer);
//                    webSocket.close(1000, "websocket finish");
//                    okHttpClient.connectionPool().evictAll();
//                    System.exit(0);
//                }
//            }
//        });
//        webSocket.send(JSONUtil.toJsonStr(request));
    }
}